""" 

    Pledge.py used in RepresentedBy Facebook application
    http://apps.facebook.com/representedby/
    
    This page is a webservice which saves a user's pledge to support transparency and returns
    the result as a JSON object
    
    Accepts one parameter:
        ids (required) - comma delimited list of Bioguide Ids
    
"""

__author__ = "Will Turnage (will @t wubbahed d0t com)"
__version__ = "0.1.0"
__copyright__ = "Copyright (c) 2009 wubbahed.com"
__license__ = "GPLv3"


import os
import wsgiref.handlers
import facebook
import const
import string

from sets import Set
from django.utils import simplejson
from facebook import FacebookError
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
from utils import fbUtil, dbUtil, Pledges

class MainHandler(webapp.RequestHandler):
    
    def get(self):
        self.post()
        
    def post(self):
        
        self.response.headers["Content-Type"] = "application/json; charset=utf-8"
        jsonOutput = {"result":"ok", "message":"", "pledges":[]}
        
        try:
            self.facebookapi = fbUtil().checkFacebookAppInstalled(self, False)
            if self.facebookapi is None:
                jsonOutput["result"] = "error"
                jsonOutput["message"] = "not logged in"
            else:
                uid = int(self.facebookapi.uid)
                myPledge = Pledges.get_or_insert("user"+str(uid), uid=uid, type="user")
                if myPledge.count == 0:
                    myPledge.count = 1
                    myPledge.put()
                    
                    theIds = self.request.get('ids', default_value=None)
                    if theIds is not None:
                        
                        legislatorIds = theIds.split(",")       
                        for legislatorId in legislatorIds:
                            if (legislatorId == "TOTAL") or (const.FRIENDLY_NAME.has_key(legislatorId)):
                                newPledge = Pledges.get_or_insert("legislator"+str(legislatorId), legislator=legislatorId, type="legislator")
                                if legislatorId != "TOTAL":
                                    jsonOutput["pledges"].append({"name":const.FRIENDLY_NAME[newPledge.legislator], "count": newPledge.count + 1})    
                                else:
                                    jsonOutput["total"] = newPledge.count + 1
                               
                                newPledge.count = newPledge.count + 1
                                newPledge.put()
                                
                        if len(jsonOutput["pledges"]) == 0:
                            jsonOutput["result"] = "error"
                            jsonOutput["message"] = "invalid parameters"
                            
                    else:
                        jsonOutput["result"] = "error"
                        jsonOutput["message"] = "missing parameters"
                           
                else:
                    jsonOutput["result"] = "error"
                    jsonOutput["message"] = "already pledged"
                
            
        except FacebookError, e:
            jsonOutput["result"] = "error"
            jsonOutput["message"] = str(e.msg)
                       
        self.response.out.write(simplejson.dumps(jsonOutput))          
  
def main():
	application = webapp.WSGIApplication([('/fb/pledge', MainHandler)],
									   debug=True)
	run_wsgi_app(application)

# load our custom filters		   
webapp.template.register_template_library('customfilters')

if __name__ == '__main__':
	main()
